package com.example.demo.controller;

import com.example.demo.entity.Admin;
import com.example.demo.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @RequestMapping("/show_login_page")
    public String show_login_page(HttpSession httpSession){
        httpSession.removeAttribute("admin");
        return "adminLogin";
    }
    @RequestMapping("/dologin")
    public String dologin(Admin admin, HttpSession httpSession){
       Admin admindb=adminService.findByAdmin(admin.getAdmin());
        if (admindb==null){
            httpSession.removeAttribute("errmsg2");
            httpSession.setAttribute("errmsg2","管理员不存在");
            return "redirect:/admin/show_login_page";
        }else if (admindb.getPassword().equals(admin.getPassword())) {
            httpSession.setAttribute("admin", admindb);
            return "redirect:/admin/show_admin_page";
        }else {
            httpSession.removeAttribute("errmsg2");
            httpSession.setAttribute("errmsg2","密码错误");
            return "redirect:/admin/show_login_page";
        }

    }
    @RequestMapping("/show_admin_page")
    public String show_admin_page(){
        return "admin";
    }
    @RequestMapping("/updatePwd")
    public String updatePwd(){
        return "updatePwd";
    }
    @RequestMapping("/doupdatePwd")
    @ResponseBody
    public Map<String,Object> doupdatePwd(HttpSession httpSession, String oldPassword, String password) throws IOException {

       Admin admin= (Admin) httpSession.getAttribute("admin");
        Map<String,Object> resultMap = new HashMap<String, Object>();
       if (oldPassword.equals(admin.getPassword())){
           admin.setPassword(password);
           adminService.updateAdmin(admin);
           resultMap.put("result","SUCCESS");
           httpSession.removeAttribute("admin");
           return resultMap;
       }
       else {
            resultMap.put("result","旧密码错误啦！");


           return resultMap;
       }

    }

}
